<?php

namespace app\admin\validate;

use think\Db;
use think\Validate;

/**
 * goods验证器
 */
class Category extends Validate
{

    protected $rule = [
        'title' => 'require|max:15',
        'description' => 'require|max:50',
        'status' => 'in:0,1',
        'parent_id' => 'require|exists:goods_category,cate_id,0',
    ];
    protected $message = [
        'name.max' => '名字不宜过长，15个汉字内适宜',
        'remark.max' => '描述不宜过长，50个汉字内适宜',
        'role_id.require' => 'role_id字段必须存在',
        'role_id.exists' => 'role_id不存在',
    ];
    protected $scene = [
        'add' => ['title', 'description','status','parent_id'],
        
    ];
    // 自定义exists规则，exists:table,字段,排除的某个值  即若验证的值与排除的值相等则返回true
    protected function exists($value, $rule, $data, $field)
    {
        if (is_string($rule)) {
            $rule = explode(',', $rule);
        }
        if (isset($rule[2]) && $value == $rule[2]) {
            return true;
        }
        $db = Db::name($rule[0]);
        $key = isset($rule[1]) ? $rule[1] : $field;
        if (strpos($key, '^')) {
            // 支持多个字段验证
            $fields = explode('^', $key);
            foreach ($fields as $key) {
                $map[$key] = $data[$key];
            }
        } elseif (strpos($key, '=')) {
            parse_str($key, $map);
        } else {
            $map[$key] = $data[$field];
        }
        if ($db->where($map)->find()) {
            return true;
        }
        return false;
    }
}
